package com.tensquare.article.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.tensquare.article.dao.ArticleDao;
import com.tensquare.article.pojo.Article;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import util.IdWorker;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Service
public class ArticleService {
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private HttpServletRequest request;

    public List<Article> findAll() {
       return articleDao.selectList(null);
    }

    public Article findById(String articleId) {
        return  articleDao.selectById(articleId);
    }

    public void save(Article article) {
        Claims claims_user = (Claims) request.getAttribute("claims_user");
        if(claims_user==null){
            throw new RuntimeException("权限不足");
        }
        String id=idWorker.nextId()+"";
        article.setId(id);
        articleDao.insert(article);
    }

    public void updateById(Article article) {
        articleDao.updateById(article);
        /*//条件修改对象的创建
        EntityWrapper<Article> wrapper=new EntityWrapper<>();
        //设置查询条件
        wrapper.eq("id",article.getId());
        //修改操作
        articleDao.update(article,wrapper);*/
    }

    public void deleteById(String articleId) {
        articleDao.deleteById(articleId);
    }

    public Page<Article> findByPage(Map<String, Object> map, Integer page, Integer size) {
        //设置查询条件
        EntityWrapper<Article>wrapper=new EntityWrapper<>();
        Set<String> keySet = map.keySet();
        for (String s : keySet) {
            wrapper.eq(map.get(s)!=null,s,map.get(s));
        }
        //设置分页参数
        Page<Article>pageData=new Page<>(page,size);
        //查询返回结果集
        List<Article> list=articleDao.selectPage(pageData,wrapper);
        //设置回返回值并返回
        pageData.setRecords(list);
        return pageData;


    }

    public void addthumbup(String articleid) {
        Article article = articleDao.selectById(articleid);
        article.setThumbup(article.getThumbup()+1);
        articleDao.updateById(article);
    }

    public void updateExamineById(Article article) {
        article.setState("1");
        System.out.println(article);
        articleDao.updateById(article);
    }
}
